<?php
namespace app\system\controller;

use app\common\model\GoodsCate;
use app\system\validate\Goods;

/**
 * Created by Goods.
 * User: Lee
 * Date: ${DATE}
 * Time: ${TIME}
 */
class Product extends Common
{
    protected $pageSize = 20;

    /**
     * 商品列表
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $keywords = input('keywords', '', 'trim');
        $cate_id = input('cate_id', 0, 'trim');
        $where = [];
        !empty($keywords) && $where['g.title'] = ['like',"%$keywords%"];
        $cateModel = new GoodsCate();
        if ($cate_id > 0) {
            $ids = $cateModel->where(['pid'=>$cate_id])->column('id');
            if (empty($ids)) {
                $where['g.cate_id'] = $cate_id;
            } else {
                $where['g.cate_id'] = ['in', $ids];
            }
        }
        $pageconfig['path'] = url("?keywords={$keywords}&cate_id={$cate_id}");
        $goods_model = new \app\common\model\Goods();
        $list = $goods_model->pageListJoinCate($where, $this->pageSize, $pageconfig, 'gc.title cate_title,g.title,g.img,g.price,g.unit_price,g.sort,g.sale_num,g.id,g.is_recommend,g.is_sale', 'g.is_recommend desc,g.sort desc,g.id desc');

        $clist = $cateModel->getList();

        $this->assign('clist', $clist);
        $this->assign('list', $list);
        return $this->fetch();

    }

    /**
     * 商品编辑
     * @param int $id
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function save($id=0)
    {
        if (isAjaxPost()) {
            $data = [
                'cate_id' => input('post.cate_id', '', 'intval'),
                'level_id' => input('post.level_id', '', 'intval'),

                'title' => input('post.title', '', 'trim'),
                'img' => input('post.img', '', 'trim'),
                'imgs' => isset($_POST['imgs']) ? $_POST['imgs'] : '',
                'spec' => isset($_POST['spec']) ? $_POST['spec'] : '',
                'price' => amountFormat(input('post.price', 0, 'floatval')),
                'unit_price' => amountFormat(input('post.unit_price', 0, 'floatval')),
                'is_recommend' => input('post.is_recommend', 0, 'intval'),
                'is_sale' => input('post.is_sale', 0, 'intval'),
                'sale_num' => input('post.sale_num', 0, 'intval'),
                'content' => input('post.content', '', 'trim'),
                'sort' => input('post.sort', 0, 'intval'),
            ];
            $cate=db('goods_cate')->find($data['cate_id']);
            if($cate['pid']){
                for ($i=$cate['layer']-1; $i >1; $i--) {
                    $cate=db('goods_cate')->where('id='.$cate['pid'])->value('id');
                    $data['category'.$i]=$cate['id'];
                }
            }else{
                $data['category1']=$cate['id']; 
            }
            if (!empty($data['imgs'])) {
                foreach ($data['imgs'] as $k => $v) {
                    if (empty($v)) {
                        unset($data['imgs'][$k]);
                    }
                }
                $data['imgs'] = json_encode($data['imgs']);
            }

            $validate = new Goods();
            if (!$validate->check($data)) {
                return $this->jsonError($validate->getError());
            }

            unset($data['id']);
            $spec = [];
            if (!empty($data['spec'])) {
                $spec = [
                    'spec' => $data['spec'],
                    'price' => $_POST['specprice']
                ];
            }
            $data['spec'] = json_encode($spec, JSON_UNESCAPED_UNICODE);
            $goods_model = new \app\common\model\Goods();
            if ($id > 0) {
                if ($goods_model->save($data, ['id'=>$id]) !== false) {
                    return $this->jsonSuccess('修改成功');
                } else {
                    return $this->jsonError('修改失败');
                }
            } else {
                if ($goods_model->insert($data)) {
                    return $this->jsonSuccess('添加成功');
                } else {
                    return $this->jsonError('添加失败');
                }
            }
        }

        $cateModel = new GoodsCate();
        $clist = $cateModel->getList();
        $this->assign('level', \app\common\model\Level::all());

        $this->assign('clist', $clist);

        if ($id > 0) {
            $info = db('goods')->where(['id'=>$id])->find();
            if (!empty($info)) {
                $info['imgs'] = json_decode($info['imgs'], true);
                $info['spec'] = json_decode($info['spec'], true);
                $this->assign('data', $info);
            }
        }

        return $this->fetch();
    }

    /**
     * @param $id
     * @param $status
     * @return \think\response\Json
     */
    public function changeStatus($id, $status) {
        if (isAjaxPost()) {
            $id = intval($id);
            $status = intval($status);
            if ($id <= 0 || !in_array($status, [0, 1])) {
                return $this->jsonError('操作失败');
            }

            $goods_model = new \app\common\model\Goods();
            if ($goods_model->save(['is_recommend' => $status], ['id'=>$id]) !== false) {
                return $this->jsonSuccess('操作成功');
            } else {
                return $this->jsonError('操作失败');
            }
        }
    }

    /**
     * @param $id
     * @param $status
     * @return \think\response\Json
     */
    public function changeSale($id, $status) {
        if (isAjaxPost()) {
            $id = intval($id);
            $status = intval($status);
            if ($id <= 0 || !in_array($status, [0, 1])) {
                return $this->jsonError('操作失败');
            }

            $goods_model = new \app\common\model\Goods();
            if ($goods_model->save(['is_sale' => $status], ['id'=>$id]) !== false) {
                return $this->jsonSuccess('操作成功');
            } else {
                return $this->jsonError('操作失败');
            }
        }
    }

    /**
     * 删除
     * @return \think\response\Json
     */
    public function del(){
        if (isAjaxPost()) {
            $id = input('post.id');

            $model = new \app\common\model\Goods();
            if ($id > 0 && $model->where('id', $id)->delete() !== false) {
                return $this->jsonSuccess('删除成功');
            } else {
                return $this->jsonError('删除失败');
            }
        }
    }

    /**
     * 批量删除
     * @return \think\response\Json
     */
    public function delAll()
    {
        if (isAjaxPost()) {
            $post = input('post.');

            if (empty($post['id']) || !is_array($post['id']) || count($post['id']) <= 0) {
                return $this->jsonError('请勾选需要删除的商品！');
            }
            $ids = $post['id'];

            $model = new \app\common\model\Goods();
            if ($model->where(['id'=>['in', $ids]])->delete() !== false) {
                return $this->jsonSuccess('删除成功');
            } else {
                return $this->jsonError('删除失败');
            }
        }
    }

    /**
     * 排序
     * */
    public function saveSort()
    {
        if (isAjaxPost()) {
            $model = new \app\common\model\Goods();
            $sort = input('post.');
            foreach ($sort as $k => $v) {
                $model->save(['sort' => $v], ['id'=>$k]);
            }
            return $this->jsonSuccess('修改成功');
        }
    }

    /**
     * 排序
     * */
    public function saveCateSort()
    {
        if (isAjaxPost()) {
            $model = new GoodsCate();
            $sort = input('post.');
            foreach ($sort as $k => $v) {
                $model->where('id', $k)->update(['sort' => $v]);
            }
            return $this->jsonSuccess('修改成功');
        }
    }
    /**
     * 删除
     * */
    public function delCate(){
        if (isAjaxPost()) {
            $id = input('post.id');

            $model = new GoodsCate();
            if ($id > 0 && $model->where('id', $id)->delete() !== false) {
                return $this->jsonSuccess('删除成功');
            } else {
                return $this->jsonError('删除失败');
            }
        }
    }

    /**
     * 批量删除
     * */
    public function delAllCate()
    {
        if (isAjaxPost()) {
            $post = input('post.');

            if (empty($post['id']) || !is_array($post['id']) || count($post['id']) <= 0) {
                return $this->jsonError('请勾选需要删除的分类！');
            }
            $ids = $post['id'];

            $model = new GoodsCate();
            if ($model->where(['id'=>['in', $ids]])->delete() !== false) {
                return $this->jsonSuccess('删除成功');
            } else {
                return $this->jsonError('删除失败');
            }
        }
    }

    /**
     * 分类列表
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function cate() {
        $cateModel = new GoodsCate();
        $clist = $cateModel->getList();
        $this->assign('list', $clist);
        return $this->fetch();
    }

    /**
     * 修改分类
     * @param int $id
     * @return mixed|\think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function cate_save($id=0) {
        $cateModel = new GoodsCate();
        if (isAjaxPost()) {
            $data = input('post.');
            if (empty($data['title'])) {
                return $this->jsonError('请填写分类名称');
            }
            if ($data['pid'] > 0 && empty($data['img'])) {
                return $this->jsonError('请上传分类图片');
            }

            if (!empty($data['img'])) {
                editImg('.' . $data['img'], 1);
            }
            unset($data['id']);

            if ($id > 0) {
                if ($cateModel->save($data, ['id'=>$id]) !== false) {
                    return $this->jsonSuccess('修改成功');
                } else {
                    return $this->jsonError('修改失败');
                }
            } else {
                if ($cateModel->insert($data)) {
                    return $this->jsonSuccess('添加成功');
                } else {
                    return $this->jsonError('添加失败');
                }
            }
        }

        if ($id > 0) {
            $info = $cateModel->where(['id'=>$id])->find()->toArray();
            $this->assign('data', $info);
        }
        $list = $cateModel->where(['pid'=>0])->column('id,title', 'id');
        $this->assign('list', $list);
        return $this->fetch();
    }
}
